//
//  HBStringListView.m
//  HBLibary
//
//  Created by Rambo on 2018/11/4.
//

#import "HBStringListView.h"
#import "NSString+HBCategory.h"
#import "UIFont+HBCategory.h"
#import "HBEdgeInsetsLabel.h"

@interface HBStringListView ()

@property (nonatomic, assign) CGSize contentSize;

@end

@implementation HBStringListView


- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        _titleFont = [UIFont systemFontOfSize:14];
        _stringInsets = UIEdgeInsetsMake(3, 3, 3, 3);
        _minimumLineSpacing = 3;
        _minimumInteritemSpacing = 3;
        _textColor = [UIColor blackColor];
        _stringBackgroundColor = [UIColor lightGrayColor];
        _contentInsets = UIEdgeInsetsZero;
        _numberOfLines = 1;
    }
    return self;
}

#pragma mark - Action

- (void)labelTap:(UITapGestureRecognizer*)tap{
    HBEdgeInsetsLabel *label = (HBEdgeInsetsLabel*)tap.view;
    if (![label isKindOfClass:[HBEdgeInsetsLabel class]]) return;
    if (!self.tapBlock) return;
    self.tapBlock(label.text, label.tag);
}

#pragma mark - set

///< 边缘间隙
- (void)setStringInsets:(UIEdgeInsets)stringInsets{
    _stringInsets = stringInsets;
    [self updateTitles];
}

///< item上下间隙
- (void)setMinimumLineSpacing:(CGFloat)minimumLineSpacing{
    _minimumLineSpacing = minimumLineSpacing;
    [self updateTitles];
}

///< item左右间隙
- (void)setMinimumInteritemSpacing:(CGFloat)minimumInteritemSpacing{
    _minimumInteritemSpacing = minimumInteritemSpacing;
    [self updateTitles];
}

///< 默认 14号字体
- (void)setTitleFont:(UIFont *)titleFont{
    _titleFont = titleFont;
    [self updateTitles];
}

///< 默认黑色
- (void)setTextColor:(UIColor *)textColor{
    _textColor = textColor;
    for (UILabel *label in self.subviews) {
        if (![label isKindOfClass:[HBEdgeInsetsLabel class]]) return;
        label.textColor = _textColor;
    }
}

///< 默认灰色
- (void)setStringBackgroundColor:(UIColor *)stringBackgroundColor{
    _stringBackgroundColor = stringBackgroundColor;
    for (UILabel *label in self.subviews) {
        if (![label isKindOfClass:[HBEdgeInsetsLabel class]]) return;
        label.backgroundColor = _stringBackgroundColor;
    }
}

- (void)setRadius:(CGFloat)radius{
    _radius = radius;
    for (UILabel *label in self.subviews) {
        if (![label isKindOfClass:[HBEdgeInsetsLabel class]]) return;
        label.layer.cornerRadius = _radius;
        label.layer.masksToBounds = YES;
    }
}

- (void)setTitles:(NSArray<NSString *> *)titles{
    _titles = titles;
    [self updateTitles];
}

///< 整体边缘间隙
- (void)setContentInsets:(UIEdgeInsets)contentInsets{
    _contentInsets = contentInsets;
    [self updateTitles];
}

- (void)setNumberOfLines:(NSInteger)numberOfLines{
    _numberOfLines = numberOfLines;
    [self updateTitles];
}

#pragma mark - layout

- (void)updateTitles{
    while (self.subviews.count) {
        [self.subviews.lastObject removeFromSuperview];
    }
    
    self.contentSize = CGSizeZero;
    if (self.titles == nil || self.titles.count == 0) {
        [self invalidateIntrinsicContentSize];
        return;
    }
    
    
    [self layoutIfNeeded];
    CGFloat maxWidth = self.frame.size.width;
    if (maxWidth == 0) {
        maxWidth = [UIScreen mainScreen].bounds.size.width;
    }
    
    CGFloat titleX = self.contentInsets.left;
    CGFloat titleY = self.contentInsets.top;
    
    CGFloat contentMaxWidth = maxWidth - self.contentInsets.left - self.contentInsets.right;
    CGFloat remainderWidth = contentMaxWidth;
    CGFloat titleMaxWidth = remainderWidth - self.stringInsets.left - self.stringInsets.right;
    CGFloat maxStringHeight = (self.numberOfLines == 0 ? MAXFLOAT : self.titleFont.hb_fontHeight * self.numberOfLines);

    for (NSInteger index = 0; index < _titles.count; index++) {
        NSString *title = _titles[index];
        if (![title isKindOfClass:[NSString class]] || [NSString hb_isEmpty:title]) continue;
        
        CGSize titleSize = [title hb_sizeWithMaxSize:CGSizeMake(titleMaxWidth, maxStringHeight) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) font:self.titleFont];
        titleSize.width += self.stringInsets.left + self.stringInsets.right + 0.5;
        titleSize.height += self.stringInsets.top + self.stringInsets.bottom + 0.5;
        if (titleSize.width > remainderWidth) {
            titleX = self.contentInsets.left;
            titleY = self.contentSize.height + self.minimumLineSpacing;
//            titleSize.width = contentMaxWidth;
        }
        
        HBEdgeInsetsLabel *label = [[HBEdgeInsetsLabel alloc] init];
        label.text = title;
        label.tag = index;
        label.userInteractionEnabled = YES;
        label.edgeInsets = self.stringInsets;
        label.numberOfLines = self.numberOfLines;
        label.textColor = self.textColor;
        label.backgroundColor = self.stringBackgroundColor;
        label.layer.cornerRadius = self.radius;
        label.layer.masksToBounds = YES;
        label.lineBreakMode = NSLineBreakByTruncatingTail;
        label.font = self.titleFont;
        
//        label.frame = CGRectMake(titleX, titleY, titleSize.width, titleSize.height);
        
        CGSize size = [label sizeThatFits:titleSize];
        if (size.width > titleSize.width) {
            NSLog(@"%@---%@",NSStringFromCGSize(size), NSStringFromCGSize(titleSize));
            size.width = (int)titleSize.width;
        }
        if (size.height > titleSize.height) {
            size.height = (int)titleSize.height;
        }
        label.frame = CGRectMake(titleX, titleY, size.width, size.height);
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap:)];
        [label addGestureRecognizer:tap];
        [self addSubview:label];
        
        CGSize contentSize = self.contentSize;
        contentSize.height = CGRectGetMaxY(label.frame);
        contentSize.width = MAX(self.contentSize.width, CGRectGetMaxX(label.frame) + self.contentInsets.right);
        self.contentSize = contentSize;
        
        
        remainderWidth = contentMaxWidth - CGRectGetMaxX(label.frame) - self.minimumInteritemSpacing;
        titleX = CGRectGetMaxX(label.frame) + self.minimumInteritemSpacing;
        titleY = label.frame.origin.y;
        
    }
    CGSize contentSize = self.contentSize;
    contentSize.height += self.contentInsets.bottom;
    self.contentSize = contentSize;
    
    [self invalidateIntrinsicContentSize];
}

- (CGSize)intrinsicContentSize{
    return self.contentSize;
}

- (CGSize)sizeThatFits:(CGSize)size{
    return self.contentSize;
}

@end
